package news.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import news.biz.UserBiz;
import news.entity.User;

public class lgoinservlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request,HttpServletResponse response)
					throws ServletException,IOException{
		PrintWriter out=response.getWriter();
		HttpSession session=request.getSession();                                                                          
		
		request.setCharacterEncoding("UTF-8");
		//response.setCharacterEncoding("UTF-8");
		
		response.setContentType("text/html;charset=UTF-8");
		
		String name=request.getParameter("username");
		String pwd=request.getParameter("userpwd");
		String autoLogin=request.getParameter("autoLogin");//多少天免登陆是否被选中，选择：on 未选择：null
		
		UserBiz userBiz=new UserBiz();
		User user=userBiz.userLogin(name, pwd);
		
		if(user!=null){
			
			if(autoLogin!=null){
				//创建cookie
				Cookie uname=new Cookie("uname",name);
				uname.setPath("/");
				uname.setMaxAge(60*60*24*14);
				//写入
				response.addCookie(uname);
				
				out.print("<script>alert('登陆成功')</script>");			
			}else{
				//创建session
				session.setAttribute("uname", name);
				out.print("<script>alert('登陆成功')</script>");			
			}
			request.getRequestDispatcher("index.jsp").forward(request,response);
			
		}else{
			out.print("<script>alert('登录失败,请重试');location.href='login.jsp'</script>");	
		}
		
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response)
					throws ServletException,IOException{
		doGet(request, response);
	}
	
	
}
